#include "login.h"
#include "ui_login.h"
#include <QNetworkRequest>
#include <QNetworkReply>
#include <url_string.h>
//#include <QJsonDocument>
//#include <QJsonObject>
#include "common.h"

extern std::string      g_token;
extern std::string      g_url;

Login::Login(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Login)
{
    ui->setupUi(this);
    m_manager = new QNetworkAccessManager(this);
    connect(m_manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(finished(QNetworkReply*)));
#ifdef QT_DEBUG
    ui->m_server->setText("http://127.0.0.1/fastcgi/ad.fcgi");
    ui->m_name->setText("root");
    ui->m_passwd->setText("admin");
    login();
#endif // DEBUG
}

Login::~Login()
{
    delete ui;
    delete m_manager;
}

void Login::login()
{
    QString     server = ui->m_server->text();
    QString     name = ui->m_name->text();
    QString     passwd = ui->m_passwd->text();
    url_string<>    url;

    // 开始登录
    url.format("%s?handler=login&user=%u&pwd=%u",
               server.toStdString().c_str(),
               name.toStdString().c_str(),
               passwd.toStdString().c_str());
    g_url = server.toStdString();
    m_manager->get(QNetworkRequest(QUrl(url.c_str())));
    // 设置登录标志
    ui->m_error->setText(_T("<font color=green>正在登录</font>"));
    disableControls(true);
  }

// disable contorl
void Login::disableControls(bool b)
{
    ui->m_server->setDisabled(b);
    ui->m_name->setDisabled(b);
    ui->m_passwd->setDisabled(b);
    ui->m_login->setDisabled(b);
}

// request end
void Login::finished(QNetworkReply *reply)
{
    disableControls(false);
    // check error
    if(reply->error())
    {
        ui->m_error->setText(_T("<font color=red>联不上网络</font>"));
        return;
    }

    // check type
    if("application/json" != reply->header(QNetworkRequest::ContentTypeHeader))
    {
        ui->m_error->setText(_T("<font color=red>服务器内部错误</font>"));
        return;
    }

    QByteArray          ba = reply->readAll();
    JSONNode            json;
    QString             err;

    if( !ad::json_parse(json, ba.data(), &err))
    {
        ui->m_error->setText("<font color=red>" + err + "</font>");
        return;
    }

    if( 0 != ad::json_get_int(json, "errno")
            || false == ad::json_is_string(json, "token") )
    {
        if(json.end() != json.find("error"))
        {
            ui->m_error->setText("<font color=red>"
                                 + ad::json_get_string(json, "error")
                                 + "</font>");
        }
        else
        {
            ui->m_error->setText("<font color=red>error</font>");
        }

        return;
    }


    // set token
    g_token = json.at("token").as_string().c_str();
    // exit dlg
    accept();
}

